import base64

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from lxml import etree
import time
import random
import os
from operation.forms import wikiForm
from operation.models import Wiki


# Create your views here.
@login_required
def addwiki(request):
    return render(request, "operation/change_wiki.html")

@login_required
def submitwiki(request):
    if request.method == "POST":
        form = wikiForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            contentarea = "".join(form.cleaned_data['contentarea'])
            tree = etree.HTML(contentarea)
            images = tree.xpath("//img/@src")
            for image in images:
                imagecontent = image.split(";base64,")
                if len(imagecontent) > 1:
                    imagename = str(int(time.time()*1000))+str(random.randint(1,1000))
                    suffix = imagecontent[0].split("/")[1]
                    imagesaveurl = os.path.join(settings.MEDIA_ROOT,imagename+"."+suffix)
                    imagegeturl = "http://"+request.get_host()+os.path.join(settings.MEDIA_URL,imagename+"."+suffix)
                    with open(imagesaveurl,'wb') as imagefile:
                        imagefile.write(base64.b64decode(imagecontent[1]))
                    contentarea = contentarea.replace(image,imagegeturl)  
            wikiid = request.POST.get("id").strip()
            if wikiid:
                wiki = Wiki.objects.get(pk=wikiid)
                wiki.contentarea = contentarea
                wiki.title = title
                wiki.save()
                return render(request,"operation/change_wiki.html",{'wiki':wiki})
            else:
                wiki = Wiki(title=title,contentarea=contentarea)
                wiki.save()
                return HttpResponseRedirect("/admin/operation/wiki/")
    else:
        form = wikiForm()
    return render(request,'operation/change_wiki.html',{'form':form})

@login_required
def viewwiki(request,wikiid):
    wiki = Wiki.objects.get(pk=int(wikiid))
    return render(request,"operation/change_wiki.html",{'wiki':wiki})